package top.zhangjianyong.thread;

import lombok.extern.slf4j.Slf4j;
import top.zhangjianyong.entity.ReptileUrl;
import top.zhangjianyong.utils.HtmlUtil;
import top.zhangjianyong.utils.HttpResult;
import top.zhangjianyong.utils.ReptileContent;
import top.zhangjianyong.utils.RequestUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;

/**
 * @author ： zhangjianyong
 * @date ： 2023/3/29 2:41 PM
 */
@Slf4j
public class ReptileCallable implements Callable<Integer> {

    private ReptileUrl reptileUrl;

    public ReptileCallable(ReptileUrl url) {
        this.reptileUrl = url;
    }

    @Override
    public Integer call() throws Exception {

        log.info("解析网页地址：{}", reptileUrl.getUrl());
        int process = 0;
        //String remark = null;
        try {
            process = process(reptileUrl);
        } catch (Exception e) {
            log.error("异常：{}-{}", reptileUrl.getId(), e.getMessage());
            log.error(e.getMessage(), e);
            process = 999;
            // remark = ExceptionUtil.getExceptionToString(e);
        } catch (Error e) {
            log.error("程序错误：{}-{}", reptileUrl.getId(), e.getMessage());
            throw e;
        }
        moveData(reptileUrl, process);

        return process;
    }

    public void moveData(ReptileUrl reptileUrl, int process) {
        try {
            if (process == 200) {
                /*请求成功入成功表*/
                ReptileContent.sucUrl(reptileUrl, process);
            } else {
                /*请求失败入失败表*/
                ReptileContent.errUrl(reptileUrl, process);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            moveData(reptileUrl,process);
        }
    }

    public static int process(ReptileUrl reptileUrl) throws IOException, SQLException {

        HttpResult result = RequestUtil.getHtml(reptileUrl);
        int status = result.getStatus();
        saveBody(result, reptileUrl);
        return status;

    }

    public static void saveBody(HttpResult result, ReptileUrl reptileUrl) throws SQLException, UnsupportedEncodingException {

        String body = result.getBody();
        /*获取当前页面信息*/
        updateHead(body, reptileUrl);
        /*跳转地址*/
        List<String> linkUrl = HtmlUtil.getLinkUrl(body);
        Set<String> linkSet = HtmlUtil.removeBlankUrl(linkUrl);
        ReptileContent.offerUrl(linkSet, reptileUrl.getUrl());
    }

    public static void updateHead(String body, ReptileUrl reptileUrl) throws SQLException {
        HtmlUtil.HtmlHead head = HtmlUtil.getHead(body);
        log.info("更新网页头信息：{};{};{}", head.title, head.keywords, head.description);
        ReptileContent.updateHead(reptileUrl, head);
    }
}
